import { NavBar, DatePicker } from "antd-mobile";
import "./index.scss";
import {useMemo, useState, useEffect} from 'react';
import classNames from "classnames";
import dayjs from 'dayjs'
import { useSelector} from 'react-redux'
import DayBill from "./components/DayBill";

export default function Month() {
  // 账期列表
  const billList = useSelector(state => state.bill.billList)
  // 控制DatePicker的显示与隐藏
  const [dataVisible, setDataVisible] = useState(false)
  const [currentDate, setCurrentDate] =  useState(dayjs(new Date()).format('YYYY-MM'))
  const [monthList, setMonthList] = useState([])
  const [dayBillList, setDayBillList] = useState({})

  // 确认时间选择框
  const confirmDate = (date) => { 
    setCurrentDate(dayjs(date).format('YYYY-MM'))
    setDataVisible(false)
    // 根据传入的时间过滤出符合当前月份的数据
    const result = filterRecordsByMonth(billList, date)
    setMonthList(result)
    setDayBillList(processDayBillList(result))
  }
 
  // 根据传入的年份及月份过滤出符合条件的数据
  const filterRecordsByMonth = (records, currentDate) => {
    // 解析目标日期字符串为Day.js实例
    const targetDate = dayjs(currentDate).startOf('month');

    // 获取目标月份和年份
    const targetMonth = targetDate.month();
    const targetYear = targetDate.year();

    // 过滤出目标月份的记录
    return records.filter(record => {
      // 解析record中的日期为Day.js实例
      const recordDate = dayjs(record.date);

      // 检查记录的月份和年份是否与目标匹配
      return recordDate.month() === targetMonth && recordDate.year() === targetYear;
  });
  }

   // 预览---// 支出   /   收入    /   结余
  const monthResult = useMemo(() => {
    // 支出   /   收入    /   结余
    const pay = monthList.filter(item => item.type === 'pay').reduce((pre, item) => pre + item.money, 0)
    const income = monthList.filter(item => item.type === 'income').reduce((pre, item) => pre + item.money, 0)
    return {
      pay,
      income,
      total: pay + income
    }
  }, [monthList])

  //  初始化数据
  useEffect(() => {
    const result = filterRecordsByMonth(billList, new Date())
    setMonthList(result)
    setDayBillList(processDayBillList(result))
  }, [billList])

  // 根据时间将数据处理为 以日期为key的对象 {'2024-07-20':[...]}
  const processDayBillList = (monthList) => {
    let result = {};
    if (monthList.length > 0) {
    monthList.forEach(item => {
      const dateKey = item.date.split('T')[0]; // 2024-07-22
      if (!result[dateKey]) {
        result[dateKey] = [];
      }
      result[dateKey].push(item)
    })
    }
    return result
  }
  return (
    
    <div className="monthlyBill">
      <NavBar className="nav" backIcon={false}>
        月度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setDataVisible(true)}>
            <span className="text">{currentDate}月账单</span>
            {/* 控制箭头 */}
            <span className={classNames('arrow', dataVisible && 'expand')}></span>
          </div>
          {/* 统计区域 */}
          <div className="twoLineOverview">
          <div className="item">
              <span className="money">{monthResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.total.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="month"
            visible={dataVisible}
            onClose={() => setDataVisible(false)}
            onConfirm={confirmDate}
            max={new Date()}
          />
        </div>
        {Object.keys(dayBillList).length > 0 && Object.keys(dayBillList).map((key) => {
          return <DayBill key={key} date={key} billData={dayBillList[key]}/>
        })}
      </div>
    </div>
  );
}
